//
//  CardScrollView.m
//  for_test
//
//  Created by Carlson Lee on 2017/6/16.
//  Copyright © 2017年 Carlson Lee. All rights reserved.
//

#import "CardScrollView.h"

@interface CardScrollView ()<UIScrollViewDelegate>
{
    NSMutableArray* _items;
}
@property(nonatomic, strong)UIScrollView* scroll;

@end


@implementation CardScrollView

- (UIScrollView *)scroll
{
    if(!_scroll){
        _scroll = [[UIScrollView alloc]init];
        [self addSubview:_scroll];
        _scroll.clipsToBounds = NO;
        _scroll.pagingEnabled = YES;
        _scroll.delegate = self;
    }
    return _scroll;
}

- (instancetype)init
{
    if(self = [super init]){
        _items = [NSMutableArray array];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame]){
    
    }
    return self;
}

- (void)setObjs:(id)objs
{
    _objs = objs;
    [_objs enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView* v = [[UIView alloc]init];
        [self.scroll addSubview:v];
        [_items addObject:v];
        [v setBackgroundColor:[UIColor redColor]];
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_items enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView* v = obj;
        CGPoint pv = [v convertPoint:v.center toView:self.superview];
        CGFloat off_x = fabsf(pv.x-self.center.x-BOUNDS_WIDTH*idx);
        if(off_x<=BOUNDS_WIDTH){
            CGFloat scale = 0.8 + (0.2-0.2/BOUNDS_WIDTH*off_x);
            v.transform = CGAffineTransformMakeScale(scale, scale);
        }
    }];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    return _scroll;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    __block CGFloat f_max = 0;
    [_items enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView* v = obj;
        v.frame = CGRectMake(f_max, 0, BOUNDS_WIDTH, BOUNDS_HEIGHT);
        f_max += BOUNDS_WIDTH;
        CGPoint pv = [v convertPoint:v.center toView:self.superview];
        CGFloat off_x = fabsf(pv.x-self.center.x-BOUNDS_WIDTH*idx);
        if(off_x<=BOUNDS_WIDTH){
            CGFloat scale = 0.8 + (0.2-0.2/BOUNDS_WIDTH*off_x);
            v.transform = CGAffineTransformMakeScale(scale, scale);
        }
    }];
    self.scroll.frame = self.bounds;
    self.scroll.contentSize = CGSizeMake(f_max, 0);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
